<template>
    <div>
        <form  @submit.prevent="onSubmit" method="post" >
            <input name="file" type="file" @change="beforeUpload">
        
            <button type="submit">上传文件</button>
        </form>
    </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import webosutils from 'webosutils';
import { layer } from "@layui/layer-vue";
import { defineProps, withDefaults, defineEmits } from 'vue';
import axios, { AxiosRequestConfig, AxiosRequestHeaders, AxiosResponse } from 'axios';
import crypto from 'crypto-js';
const url = ref("");
const para = ref({}) as any;
const file = ref(null);
interface IfileuploadProps {
    config: any,callback:Function
}
const props = withDefaults(defineProps<IfileuploadProps>(), {
    config: Object,callback:Function
});
const onSubmit = () => {
    var f = new FormData() as any;
    f.append("name", para.value.name);
    f.append("filesize", para.value.filesize);
    f.append("file", file.value);
    http.uploadpost(url.value,f,"正在上传",{ headers: { 'Content-Type': 'multipart/form-data' } }).then((res:any) => {
        console.log(res);
        if (res>0) {
          
            layer.msg('上传成功', { icon: 2 });
            props.callback(res,"callback");
        }
    }).catch((res:any) => {
        layer.msg('上传失败', { icon: 2 });
    })
    // axios.post(url.value, f, { headers: { 'Content-Type': 'multipart/form-data' } }).then((res:any) => {
    //    console.log(res);
    //     if (res.data) {

    //     }
    // }).catch((res:any) => {

    // });
    //webosutils.http.post(url.va}lue, f, "请稍等",{}).then((res:any) => {
    //     if (res.success) {

    //     }

    // }).catch((res:any) => {

    // })
}
const doneHandle = (result: any) => {
    // data.value = JSON.parse(result.data);
};

const beforeUpload = (event: any) => {
    file.value = event.target.files[0];
    //检查文件指纹
    if (file.value) {
        const reader = new FileReader();
        reader.readAsDataURL(file.value);
        reader.onload = () => {
            let buffer = new Uint8Array(reader.result).buffer;
            let hash = crypto.MD5(buffer).toString();
            console.log(hash);
           webosutils.http.post("/v1/api/ctdisk/upload", { folder_id: props.config.folder_id, checksum: hash, size: file.size, name: file.name }, "请稍等").then((res:any) => {
                if (res.success) {
                    url.value = res.data.upload_url;
                    para.value = { name: file.value.name, filesize: file.value.size }
                }

            }).catch((res:any) => {

            })
        };
    }
    // var isOver = false;
    // if (file.size > 1000) {
    //     isOver = true;
    //     layer.msg(`file size over 1000 KB`, { icon: 2 })
    // }
    //  return new Promise((resolver) => resolver(true));
}
</script>